package dome_003;

/**
 * <p>Description: [synchronized关键字,对某个对象加锁]</p>
 * Created on 2020/12/3
 *
 * @author <a href="mailto: 819712047@qq.com">谢振东 </a>
 * @version 1.0
 */
public class Demo003_01 {

    private static int count = 10;

    public synchronized static void test() {
        //这里等同于synchronized(Demo003_01.class)
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName() + "已获取锁");
        count--;
        System.out.println(Thread.currentThread().getName() + " count = " + count);
    }

    public static void test2() {
        //考虑一下这里写synchronize(this)是否可以
        synchronized (Demo003_01.class) {
            try {
                Thread.sleep(1000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "已获取锁");
            count--;
            System.out.println(Thread.currentThread().getName() + " count = " + count);
        }
    }

    public static void main(String[] args) {
        Thread thread1 = new Thread(new SyncAddRunnable());
        Thread thread2 = new Thread(new SyncAddRunnable());

        thread1.setName("thread1");
        thread2.setName("thread2");

        thread1.start();
        thread2.start();
    }

    public static class SyncAddRunnable implements Runnable {

        @Override
        public void run() {
            System.out.println(String.format("运行线程开始-" + Thread.currentThread().getName()));
            Demo003_01.test();
            Demo003_01.test2();
            System.out.println(String.format("运行线程结束-" + Thread.currentThread().getName()));
        }
    }
}
